const fs = require('fs');
const accessTokenJson = require('./access_token');
const wxconfig = require('./config');
const models = require('./../mongodb/schemas');


const { aget, apost } = require('./../utils/request');
const { getFileForm } = require('./../utils')

class Wechat {

  constructor() {

    this.appID = wxconfig.appID;
    this.appSecret = wxconfig.appSecret;
    this.init();
  }

  async init() {

    await this.initAccessToken();// this.accessToken;
    this.getUserListInfo();
  }

  initAccessToken() {

    if(!accessTokenJson.access_token || accessTokenJson.expires_time < new Date().getTime()) {// access_token无效
      console.log('access_token无效')
      return this.updateAccessToken();
    } else {
      console.log('access_token有效');
      return this.accessToken = accessTokenJson.access_token;
    }
  }


  // =========================wx api============================

  updateAccessToken() {

    return aget('token', {
      grant_type: 'client_credential',
      appid: this.appID,
      secret: this.appSecret
    }).then(res => {

      const { access_token, expires_in } = res.data;

      const temp = {
        access_token,
        expires_in,
        expires_time: new Date().getTime() + expires_in * 1000
      }

      fs.writeFileSync(__dirname + '/access_token.json', JSON.stringify(temp));
      console.log('刷新了access_token');
      return this.accessToken = access_token;
    });
  }

  getUserList() {

    return this.aget('user/get', {
      // next_openid 关注者超过10000需要填写
    }).then(res => this.userList = res.data.data.openid)
    .catch(err => this.catchError(err));
  }

  getUserInfo(openid) {

    return this.aget('user/info', {
      openid,
      lang: 'zh_CN'// zh_CN 简体，zh_TW 繁体，en 英语
    }).then(res => res.data);
  }

  async uploadMediaImg(file) {// 图文内图片

    const { form, headers } = await getFileForm(file);
    return this.apost('/media/uploadimg', form, {}, { headers });
  }

  async uploadMedia(file, type) {

    const { form, headers } = await getFileForm(file);
    form.append('type', type);
    return this.apost('/media/upload', form, {}, { headers });
  }

  async addMaterial(file, type) {

    const { form, headers } = await getFileForm(file);
    form.append('type', type);
    return this.apost('/material/add_material', form, {}, { headers });
  }

  sendMessage() {

    const data = {
      "touser":[
        "oIMkx1fAV_3ZpX9TF7fjNbTH3ahI", 
        "oIMkx1V_tRhLstTFjWn4FkYZUSvY"
      ],
      "mpnews":{
         "media_id":"d24VG7z-D4aF_eRXEH2ZWpHpcdkgNFa-ijpjLzj7BLTRFao9FK9KSZjLwaqO9GMu"
      },
      "msgtype":"mpnews",
      "send_ignore_reprint":0
    }

  //   {
  //     "filter":{
  //        "is_to_all":false,
  //        "tag_id":2
  //     },
  //     "mpnews":{
  //        "media_id":"123dsdajkasd231jhksad"
  //     },
  //      "msgtype":"mpnews",
  //      "send_ignore_reprint":0
  //  }

    return this.apost('/message/mass/send', data);
  }

  uploadMediaNews() {

    const data = {
      articles: [{
        "thumb_media_id":"Tv67rPUo6nfQ55C7boV_z0_094yNWezFEQf56ehP38ieWZ7y_ubeDEpp4gLG4JEU",
        "author":"xxx",        
        "title":"Happy Day1",         
        "content_source_url":"www.qq.com",        
        "content":"content",         
        "digest":"digest",
        "show_cover_pic":1,
        "need_open_comment":1,
        "only_fans_can_comment":1
      }, {
        "thumb_media_id":"Tv67rPUo6nfQ55C7boV_z0_094yNWezFEQf56ehP38ieWZ7y_ubeDEpp4gLG4JEU",
        "author":"xxx",        
        "title":"Happy Day2",         
        "content_source_url":"www.qq.com",        
        "content":"content",         
        "digest":"digest",
        "show_cover_pic":1,
        "need_open_comment":1,
        "only_fans_can_comment":1
      }, {
        "thumb_media_id":"Tv67rPUo6nfQ55C7boV_z0_094yNWezFEQf56ehP38ieWZ7y_ubeDEpp4gLG4JEU",
        "author":"xxx",        
        "title":"Happy Day3",         
        "content_source_url":"www.qq.com",        
        "content":"content",         
        "digest":"digest",
        "show_cover_pic":1,
        "need_open_comment":1,
        "only_fans_can_comment":1
      }]
    }
    return this.apost('/media/uploadnews', data);
  }


  // =============================business============================

  async getUserListInfo() {

    await this.getUserList();
    const promises = this.userList.map(openid => this.getUserInfo(openid));

    Promise.all(promises).then(infos => {
      fs.writeFileSync(__dirname + '/../temp_data/userlist.json', JSON.stringify(infos));
      models.user.save(infos);
    });
  }



  // =========================base util=================================

  aget(...args) {

    if(!args[1]) args[1] = {}

    Object.assign(args[1], { access_token: this.accessToken });
    return aget(...args);
  }

  apost(...args) {

    if(!args[2]) args[2] = {}

    Object.assign(args[2], { access_token: this.accessToken });
    return apost(...args);
  }

  catchError(err) {

    Promise.resolve()
    .then(() => {

      switch(err.code) {
        case 42001: return this.updateAccessToken();break;
        default:;
      }
    }).catch(err => console.log(err));
  }
}

module.exports = Wechat;